package org.zuel.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.zuel.entity.User;
import org.zuel.mapper.UserMapper;
import org.zuel.service.CommonRefService;
import org.zuel.util.ResponseUtil;
import org.zuel.vo.RecordVO;
import org.zuel.web.*;
import org.zuel.exception.ParameterException;
import org.zuel.entity.Record;
import org.zuel.mapper.RecordMapper;
import org.zuel.service.IRecordService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;


/**
 *  服务实现类
 *
 * @author ikun
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements IRecordService {
    @Autowired
    CommonRefService commonRefService;
    @Override
    public Object list(SelectRecord selectRecord) {
        List<RecordVO> vos = new LinkedList<>();
        List<Integer> userIds = new LinkedList<>();
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        if (selectRecord.getStartTime() != null) {
            queryWrapper.ge("add_time", selectRecord.getStartTime()); // 大于等于 startTime
        }
        if (selectRecord.getEndTime() != null) {
            queryWrapper.le("add_time", selectRecord.getEndTime()); // 小于等于 endTime
        }
        List<Record> records = baseMapper.selectList(queryWrapper);
        records.forEach(record -> {
            //每次循环，都是处理一个model，但是组装会需要这个model的参数来查找新的参数
            RecordVO vo = new RecordVO();
            // 拷贝model中与vo属性名相同值
            BeanUtils.copyProperties(record, vo);//方法类，首先拷贝
            vos.add(vo);
            if(!userIds.contains(record.getUserId())) {//这里看似多余，实则很关键，否则后面的map构建会很复杂
                //这里是构建不重复的Id list，便于后面直接构建
                userIds.add(record.getUserId());
            }
        });
        Map<Integer, User> refUser = commonRefService.refUser(userIds);//这里是建立id与name链接的位置
        vos.forEach(vo -> {//补充值
            if(refUser.get(vo.getUserId()) != null) {//补充值
                vo.setUserName(refUser.get(vo.getUserId()).getName());
            }
        });
        return ResponseUtil.ok(vos);
    }

    @Override
    public JsonResult read(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象为空");
        }
        Record record = baseMapper.selectById(id);
        return JsonResult.ok().setData(record);
    }

    @Override
    public JsonResult add(Record record) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserId = authentication.getName(); // 获取当前登录用户的 username
        if(currentUserId==null){
            throw new ParameterException("用户状态异常");
        }
        record.setAddTime(LocalDateTime.now());
        record.setUserId(Integer.valueOf(currentUserId));
        baseMapper.insert(record);
        return JsonResult.ok("添加成功");
    }

    @Override
    public JsonResult update(Record record) {
        if (record == null) {
            throw new ParameterException("参数对象为空");
        }

        if (record.getId() == null) {
            throw new ParameterException("参数对象id为空");
        }

        baseMapper.updateById(record);
        return JsonResult.ok("修改成功");
    }

    @Override
    public JsonResult delete(Integer[] ids) {
        if (ids == null) {
            throw new ParameterException("参数对象为空");
        }

        if (ids != null || ids.length > 0) {
            baseMapper.deleteBatchIds(Arrays.asList(ids));
        }
        return JsonResult.ok("删除成功");
    }
    @Autowired
    UserMapper userMapper;
    @Override
    public JsonResult readPersonally(SelectRecord selectRecord) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserId = authentication.getName(); // 获取当前登录用户的 username
        if (currentUserId == null) {
            throw new ParameterException("用户状态异常");
        }

        // 创建 QueryWrapper
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", currentUserId); // 确保记录属于当前登录用户

        // 检查 startTime 和 endTime 是否有值
        if (selectRecord.getStartTime() != null) {
            queryWrapper.ge("add_time", selectRecord.getStartTime()); // 大于等于 startTime
        }
        if (selectRecord.getEndTime() != null) {
            queryWrapper.le("add_time", selectRecord.getEndTime()); // 小于等于 endTime
        }

        // 查询多条记录
        List<Record> records = baseMapper.selectList(queryWrapper);

        return JsonResult.ok().setData(records);
    }
}